package com.fast.modules.websocket.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.fast.common.exception.FCException;
import com.google.common.collect.Lists;

import cn.hutool.core.util.StrUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
@Data
public class UserService {
	
	// 关系
	private ConcurrentHashMap<String, String> onlineRelation;

	public UserService() {
		onlineRelation = new ConcurrentHashMap<>();
	}

	/**
     * 返回每个坐席的在线会话数量
	 * 
	 * @return
	 */
	public Map<String, List<String>> getSeatSession() {

		Map<String, List<String>> result = new HashMap<>();

		onlineRelation.entrySet().stream().forEach(entry -> {
			String seatID = entry.getValue();
			String clientID = entry.getKey();
			result.merge(seatID, Lists.newArrayList(clientID), (b, t) -> {
				b.add(clientID);
				return b;
			});
		});

		return result;
	}

    /**
     *     返回每个坐席的在线会话数量
	 * 
	 * @return
	 */
	public Map<String, Integer> getSeatSessionSize() {

		Map<String, Integer> result = new HashMap<>();

		onlineRelation.entrySet().stream().forEach(entry -> {
			String seatID = entry.getValue();
			result.merge(seatID, 1, (b, t) -> {
				return ++b;
			});
		});

		return result;
	}

	/**
	 * 根据坐席ID获取该坐席的会话数量
	 * @param seatID
	 * @return
	 */
	public long getSeatSessionSize(String seatID) {

		return onlineRelation.entrySet().stream().filter(entry -> {
			return StringUtils.endsWith(entry.getValue(), seatID);
		}).count();
	}

	/**
	 * 增加在线用户绑定关系
	 */
	public boolean addGroup(String userId, String seatId) {
		
		
		log.debug("增加绑定关系 客户ID" + userId + " 坐席ID:" + seatId);
		
		if (StrUtil.isAllBlank(userId, seatId)) {
			throw new FCException("userId and seatId is null!");
		}
		onlineRelation.put(userId, seatId);
		/**
		 * 验证有没有
		 */
		if (!onlineRelation.containsKey(userId)) {
			return false;
		}

//        if (onlineRelation.containsValue(seatId)) {
//            if (seatId.equals(sessionSize.get(seatId))){
//                atomicInteger.incrementAndGet();
//            }
//            sessionSize.put(seatId, atomicInteger);
//        }
		return true;
	}

}
